package com.stage.controller;


import com.stage.dtos.ObjectColmnsDTO;
import com.stage.service.ObjectCrudService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Map;

/**
 * Created by Stage on 2017/4/14.
 */
@Controller
public class ObjectController {
    private ObjectCrudService service = new ObjectCrudService();
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }
    @RequestMapping(value="/Json/GetObjectName", method=RequestMethod.GET)
    @ResponseBody
    public ArrayList<String> getObjectName() {
        return service.getAllObejctName();
    }
    @RequestMapping(value="/Json/GetObjectColumns", method=RequestMethod.GET)
    @ResponseBody
    public ArrayList<ObjectColmnsDTO> getObjectColumns(@RequestParam String objectName) {
        ArrayList<ObjectColmnsDTO> result = new ArrayList<>();
        Map<String, String> nameMap = service.getObjectColumns(objectName);
        for (Map.Entry<String, String> entry : nameMap.entrySet()) {
            ObjectColmnsDTO temp = new ObjectColmnsDTO();
            temp.title = entry.getKey();
            temp.dataIndex = entry.getValue();
            result.add(temp);
        }
        return result;
    }
    @RequestMapping(value="/Json/GetObjectData", method=RequestMethod.POST)
    @ResponseBody
    public ArrayList<Object> getObjectData(@RequestParam String objectName) {
      return service.getObjectData(objectName);
    }
    @RequestMapping(value="/Json/DeleteObjectData", method=RequestMethod.DELETE)
    @ResponseBody
    public ArrayList<Object> deleteObjectData(@RequestParam String objectName,@RequestParam Integer id) {
        if(service.deleteObjectData(objectName,id)){
            return service.getObjectData(objectName);
        }else {
            return  null;
        }

    }
    @RequestMapping(value="/Json/AddObject", method=RequestMethod.GET)
    @ResponseBody
    public ArrayList<Object> addObjectData(HttpServletRequest request, @RequestParam() String objectName) {
        return service.AddObjectData(objectName);
    }
    @RequestMapping(value="/Json/UpdateObject", method=RequestMethod.GET)
    @ResponseBody
    public ArrayList<Object> updateObjectData(HttpServletRequest request, @RequestParam() String objectName) {
        return service.updateObjectData(objectName);
    }
}